package com.feign.core.mybatis;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 自定义sql拦截器
 */
@Slf4j
@Component
public class CustomInterceptor  implements InnerInterceptor {


    @Resource
    private TableMetadataService tableMetadataService;

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) {
        String commandType = ms.getSqlCommandType().name();
        if (SqlCommandType.UPDATE.name().equals(commandType) || SqlCommandType.INSERT.name().equals(commandType)) {
            BoundSql boundSql = ms.getSqlSource().getBoundSql(parameter);
            String originalSql = boundSql.getSql();
            log.info("原始sql为:{}", originalSql);
            MetaObject metaObject = SystemMetaObject.forObject(parameter);
            Object object = metaObject.getOriginalObject();
            String tableName = tableMetadataService.getTableName(object.getClass());
            List<String> tableColumns = tableMetadataService.getColumnsForTable(tableName);
            log.info("表名:{},数据库实际字段:{}", tableName, tableColumns);
        }
    }


}
